package top.lrshuai.websocket.ws.utils;

import com.alibaba.fastjson.JSON;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.stereotype.Component;
import top.lrshuai.websocket.ws.entity.WebSocketDTO;

/**
 * 发送数据工具类
 */
@Component
public class MessageSender {

    private ChannelGroupUtil channelGroupUtil=ChannelGroupUtil.getInstance();

    /**
     * 发送给 具体用户
     *
     * @param userId
     * @param webSocketDTO
     */
    public void sendMessage(String userId, WebSocketDTO webSocketDTO) {
        Channel channel = channelGroupUtil.getChannelByUserId(userId);
        this.sendMessage(channel,webSocketDTO);
    }

    /**
     * 单发消息
     * @param channel
     * @param webSocketDTO
     */
    public void sendMessage(Channel channel, WebSocketDTO webSocketDTO) {
        if(channel!=null) {
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(webSocketDTO)));
        }
    }

    /**
     * 群发消息
     * @param webSocketDTO
     */
    public void sendAllMessage(WebSocketDTO webSocketDTO){
        channelGroupUtil.getChannelGroup().writeAndFlush( new TextWebSocketFrame(JSON.toJSONString(webSocketDTO)));
    }

}
